/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package IU;

import Logica.Caballo;
import Logica.Carrera;
import Logica.Fachada;
import Logica.Hipodromo;
import Logica.Jornada;
import Logica.Participante;
import Utilidades.ManejoFechas;
import Utilidades.Observable;
import Utilidades.Observador;
import java.util.ArrayList;
import java.util.Date;
import javax.swing.JOptionPane;

/**
 *
 * @author Javier Arzarello
 */
public class CaballosSeleccionar extends javax.swing.JDialog implements Observador {

    public final Hipodromo hs = PanelPrincipal.getInstancia().getHipodromoSeleccionado();
    /**
     * Creates new form CaballosSeleccionar
     */
    public CaballosSeleccionar(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
        Fachada.getInstancia().agregar(this);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        lblCarreraNro = new javax.swing.JLabel();
        lblFecha = new javax.swing.JLabel();
        lblCarreraData = new javax.swing.JLabel();
        lblFechaData = new javax.swing.JLabel();
        jScrollPane1 = new javax.swing.JScrollPane();
        lstCaballosParicipantes = new javax.swing.JList();
        jLabel1 = new javax.swing.JLabel();
        jLabel2 = new javax.swing.JLabel();
        jScrollPane2 = new javax.swing.JScrollPane();
        lstCaballosSeleccion = new javax.swing.JList();
        btnSeleccionar = new javax.swing.JButton();
        lblNumeroCarreraAMostrar = new javax.swing.JLabel();
        lblFechaAMostrar = new javax.swing.JLabel();
        btnAceptar = new javax.swing.JToggleButton();
        btnCancelar = new javax.swing.JToggleButton();
        btnEliminar = new javax.swing.JButton();
        jSeparator1 = new javax.swing.JSeparator();
        jSeparator2 = new javax.swing.JSeparator();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        lblCarreraNro.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblCarreraNro.setText("Carrera N°:");

        lblFecha.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        lblFecha.setText("Fecha:");

        lstCaballosParicipantes.setSelectionMode(javax.swing.ListSelectionModel.SINGLE_SELECTION);
        jScrollPane1.setViewportView(lstCaballosParicipantes);

        jLabel1.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel1.setText("Caballos participantes:");

        jLabel2.setFont(new java.awt.Font("Tahoma", 1, 11)); // NOI18N
        jLabel2.setText("Seleccione caballos:");

        jScrollPane2.setViewportView(lstCaballosSeleccion);

        btnSeleccionar.setText("Seleccionar");
        btnSeleccionar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnSeleccionarActionPerformed(evt);
            }
        });

        btnAceptar.setText("Aceptar");
        btnAceptar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnAceptarActionPerformed(evt);
            }
        });

        btnCancelar.setText("Cancelar");
        btnCancelar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnCancelarActionPerformed(evt);
            }
        });

        btnEliminar.setText("Eliminar");
        btnEliminar.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                btnEliminarActionPerformed(evt);
            }
        });

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jSeparator2)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblCarreraNro)
                        .addGap(151, 151, 151)
                        .addComponent(lblNumeroCarreraAMostrar)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(lblCarreraData))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(lblFecha)
                        .addGap(18, 18, 18)
                        .addComponent(lblFechaData)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(lblFechaAMostrar, javax.swing.GroupLayout.PREFERRED_SIZE, 149, javax.swing.GroupLayout.PREFERRED_SIZE))
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel2)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addGroup(layout.createSequentialGroup()
                                .addComponent(btnAceptar, javax.swing.GroupLayout.DEFAULT_SIZE, 86, Short.MAX_VALUE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                                .addComponent(btnCancelar, javax.swing.GroupLayout.PREFERRED_SIZE, 79, javax.swing.GroupLayout.PREFERRED_SIZE))
                            .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnSeleccionar))
                    .addComponent(jSeparator1)
                    .addGroup(layout.createSequentialGroup()
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 0, Short.MAX_VALUE)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addComponent(btnEliminar)))
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(layout.createSequentialGroup()
                .addContainerGap()
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblCarreraNro)
                    .addComponent(lblCarreraData)
                    .addComponent(lblNumeroCarreraAMostrar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(lblFecha)
                    .addComponent(lblFechaData)
                    .addComponent(lblFechaAMostrar, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addComponent(jSeparator1, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel1)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnEliminar))
                .addGap(9, 9, 9)
                .addComponent(jSeparator2, javax.swing.GroupLayout.PREFERRED_SIZE, 10, javax.swing.GroupLayout.PREFERRED_SIZE)
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jLabel2)
                    .addComponent(jScrollPane2, javax.swing.GroupLayout.PREFERRED_SIZE, 100, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addComponent(btnSeleccionar))
                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                .addGroup(layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                    .addComponent(btnAceptar)
                    .addComponent(btnCancelar))
                .addContainerGap())
        );

        setBounds(0, 0, 416, 374);
    }// </editor-fold>//GEN-END:initComponents

    private void btnSeleccionarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnSeleccionarActionPerformed

        // TODO add your handling code here:
        seleccionarCaballo();
    }//GEN-LAST:event_btnSeleccionarActionPerformed

    private void btnCancelarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnCancelarActionPerformed
        // TODO add your handling code here:
        // Se borra la carrera antes seleccionada
        CerrarYBorrarCarrera();
    }//GEN-LAST:event_btnCancelarActionPerformed

    private void btnEliminarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnEliminarActionPerformed
        // TODO add your handling code here:
        eliminarCaballo();
    }//GEN-LAST:event_btnEliminarActionPerformed

    private void btnAceptarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_btnAceptarActionPerformed
        // TODO add your handling code here:
        if (lstCaballosParicipantes.getModel().getSize() <= 1) {
            JOptionPane.showMessageDialog(null, "Debe seleccionar al menos 2 caballos participantes");
        } else {
            dispose();
    }//GEN-LAST:event_btnAceptarActionPerformed
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JToggleButton btnAceptar;
    private javax.swing.JToggleButton btnCancelar;
    private javax.swing.JButton btnEliminar;
    private javax.swing.JButton btnSeleccionar;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JScrollPane jScrollPane2;
    private javax.swing.JSeparator jSeparator1;
    private javax.swing.JSeparator jSeparator2;
    private javax.swing.JLabel lblCarreraData;
    private javax.swing.JLabel lblCarreraNro;
    private javax.swing.JLabel lblFecha;
    private javax.swing.JLabel lblFechaAMostrar;
    private javax.swing.JLabel lblFechaData;
    private javax.swing.JLabel lblNumeroCarreraAMostrar;
    private javax.swing.JList lstCaballosParicipantes;
    private javax.swing.JList lstCaballosSeleccion;
    // End of variables declaration//GEN-END:variables

    public void cargarCaballos() {
        String fe = lblFechaAMostrar.getText();
        ManejoFechas mf = new ManejoFechas();
        Date fechaCarrera = mf.convertir(fe);//RECUPERO FECHA DE CARRERA

        ArrayList<Caballo> caballos = Fachada.getInstancia().getCaballos();
        ArrayList<Caballo> caballosSinCarreras = new ArrayList();

        for (Caballo c : caballos) {
            if (!Fachada.getInstancia().buscarCaballosenJornadas(fechaCarrera, c)) {
                caballosSinCarreras.add(c);
            }
        }
        if (caballosSinCarreras.isEmpty()) {
            btnSeleccionar.setEnabled(false);
        }
        lstCaballosSeleccion.setListData(caballosSinCarreras.toArray());
    }

    public void mostrarFecha(String fecha) {
        lblFechaAMostrar.setText(fecha);
    }

    public void mostrarNroCarrera(int numero) {
        String n = String.valueOf(numero);
        lblNumeroCarreraAMostrar.setText(n);
    }

    private void seleccionarCaballo() {
        try {
            ArrayList<String> participantes = new ArrayList();
            //Hipodromo h = pp.getHipodromoSeleccionado();//RECUPERO HIPODROMO
            Caballo c = Fachada.getInstancia().cargarCaballo(lstCaballosSeleccion.getSelectedValue().toString());//RECUPERO CABALLO

            String fe = lblFechaAMostrar.getText();
            ManejoFechas mf = new ManejoFechas();
            Date fechaCarrera = mf.convertir(fe);//RECUPERO FECHA DE CARRERA

            Jornada j = hs.buscarJornada(fechaCarrera);
            Carrera carrera = j.buscarCarrera(Integer.parseInt(lblNumeroCarreraAMostrar.getText()));//BUSCO LA CARRERA

            String numeroCaballo = JOptionPane.showInputDialog(this, "Ingrese el número para el caballo: ");
            ValidarNumeroCaballo(numeroCaballo);
            String dividendoCaballo = JOptionPane.showInputDialog(this, "Ingrese el dividendo para el caballo: ");
            ValidarDividendo(dividendoCaballo);
            //Participante p = new Participante(c, Integer.parseInt(numeroCaballo), Integer.parseInt(dividendoCaballo));//CREO EL PARTICIPANTE DE LA CARRERA
            Fachada.getInstancia().agregarParticipante(carrera, 
                    new Participante(c, Integer.parseInt(numeroCaballo), Integer.parseInt(dividendoCaballo)));
            //carrera.agregarParticpante(p);
            for(Participante p:carrera.getParticipantes()){
                participantes.add(formatearParticipante(p));
            }
                lstCaballosParicipantes.setListData(participantes.toArray());
            //lstCaballosParicipantes.setListData(carrera.getParticipantes().toArray());
            //cargarCaballos();
            
        } catch (Exception ex) {
            JOptionPane.showMessageDialog(null, ex.getMessage());
        }
    }

    private void eliminarCaballo() {

        String participante = lstCaballosParicipantes.getSelectedValue().toString();
        Participante p = (Participante) lstCaballosParicipantes.getSelectedValue();
        System.out.println(p.getCaballo().getNombre());

        if (participante == null) {
            JOptionPane.showMessageDialog(null, "No se seleccionó ningun caballo");
        } else {

            String separado[] = participante.split(" - ");

            String fe = lblFechaAMostrar.getText();
            ManejoFechas mf = new ManejoFechas();
            Date fechaCarrera = mf.convertir(fe);//RECUPERO FECHA DE CARRERA

            Jornada j = hs.buscarJornada(fechaCarrera);
            Carrera carrera = j.buscarCarrera(Integer.parseInt(lblNumeroCarreraAMostrar.getText()));//BUSCO LA CARRERA
            carrera.eliminarParticipante(separado[0]);

            lstCaballosParicipantes.setListData(carrera.getParticipantes().toArray());
            cargarCaballos();
        }
    }

    private void ValidarNumeroCaballo(String numeroCaballo) throws Exception {
        int numC = Integer.parseInt(numeroCaballo);
        if (numC < 1 || numC > 99999) {
            throw new Exception("Número de caballo inválido");
        }
        for (int i = 0; i < lstCaballosParicipantes.getModel().getSize(); i++) {
            Object item = lstCaballosParicipantes.getModel().getElementAt(i);
            Participante par = (Participante) item;
            if (par.getNumero() == numC) {
                throw new Exception("Número de caballo inválido");
            }
        }
    }

    private void ValidarDividendo(String dividendo) throws Exception {
        int num = Integer.parseInt(dividendo);
        if (num < 1) {
            throw new Exception("El dividendo debe ser mayor que 1");
        }
    }

    private void CerrarYBorrarCarrera() {
        // mejorar y crear una nueva variable de carrera seleccionada
        String fe = lblFechaAMostrar.getText();
        ManejoFechas mf = new ManejoFechas();
        Date fechaCarrera = mf.convertir(fe);//RECUPERO FECHA DE CARRERA
        
        Jornada j = hs.buscarJornada(fechaCarrera);
        Carrera carrera = j.buscarCarrera(Integer.parseInt(lblNumeroCarreraAMostrar.getText()));//BUSCO LA CARRERA
        j.eliminarCarrera(carrera);
        dispose();
    }
    
    private String formatearParticipante (Participante p) {
        return p.getCaballo().getNombre() + " - N°: " + p.getNumero();
    }

    @Override
    public void actualizar(Observable origen, Object param) {
        if(param.equals(Fachada.Evento.CABALLO_CARRERA))
            cargarCaballos();
    }
}
